import router from '@/router'
import axios, {AxiosInstance, AxiosResponse} from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'X-Requested-With': 'XMLHttpRequest'
  }
})

// 控制登录过期的锁
let isRefreshing = false
// 请求拦截器
service.interceptors.request.use((config) => {
  if (!config?.headers) {
    throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
  }
  // 请求头添加token
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(async (response: AxiosResponse) => {
  // console.log('response',response)
  const status: number = response.status
  if (!status || status === 200) {
    return response.data
  }
  if (status === 401) {
    // 防止多次弹出登录框
    if (isRefreshing) return Promise.reject(response.data)
    // 清除本地过去的登录状态
    ElMessageBox.confirm('登录状态已过期，请重新登录', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 跳转到登录页
      router.push('/login')
    }).catch(() => {
      // 抛出异常
    }).finally(() => {
      isRefreshing = false
    })
    // 在内部消化掉这个业务异常
    return Promise.reject(response)
  }

  // 其他错误情况
  ElMessage.error(response.data.msg || '请求失败，请稍后重试')
  return Promise.reject(response.data)
}, (error: any) => {
  console.log('error',error)
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = "请求错误(400)"
        break
      case 401:
        error.message = "未授权,请登录(401)"
        break
      case 403:
        error.message = "拒绝访问(403)"
        break
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`
        break
      case 405:
        error.message = "请求方法未允许(405)"
        break
      case 408:
        error.message = "请求超时(408)"
        break
      case 500:
        error.message = "服务器内部错误(500)"
        break
      case 501:
        error.message = "服务未实现(501)"
        break
      case 502:
        error.message = "网络错误(502)"
        break
      case 503:
        error.message = "服务不可用(503)"
        break
      case 504:
        error.message = "网络超时(504)"
        break
      case 505:
        error.message = "HTTP版本不受支持(505)"
        break
      default:
        error.message = `连接错误: ${error.message}`
    }
  } else {
    if (error.message == "Network Error") error.message == "网络异常，请检查后重试！"
    error.message = "连接到服务器失败，请联系管理员"
  }
  ElMessage.error(error.message)
  return Promise.reject(new Error(error.message))
})

export default service